package com.magictower.primary.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.magictower.primary.R;
import com.magictower.primary.adapter.BlackCallBaseAdapter;
import com.magictower.primary.bean.BlackNumberInfo;
import com.magictower.primary.db.dao.BlackNumberDao;

import java.util.List;

public class CallSafe2Activity extends AppCompatActivity {
    private LinearLayout pb;
    private ListView listView;

    private List<BlackNumberInfo> list;
    private BlackNumberDao dao;
    private int total;
    /**
     * 开始的位置
     */
    private int mStartIndex = 0;
    /**
     * 每页展示10条数据
     */
    private int maxCount = 10;
    private BlackCallBaseAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call_safe2);
        dao = new BlackNumberDao(CallSafe2Activity.this);

        initUI();
        initData();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            pb.setVisibility(View.INVISIBLE);
            if (adapter == null) {
                adapter = new BlackCallBaseAdapter(CallSafe2Activity.this, list);
                listView.setAdapter(adapter);
            } else {
                adapter.notifyDataSetChanged();
            }
        }
    };

    private void initUI() {
        pb = (LinearLayout) findViewById(R.id.ll_pb);
        pb.setVisibility(View.VISIBLE);
        listView = (ListView) findViewById(R.id.list_view);

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            //状态改变时候回调的方法

            /**
             *
             * @param view
             * @param scrollState  表示滚动的状态
             *
             *                     AbsListView.OnScrollListener.SCROLL_STATE_IDLE 闲置状态
             *                     AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL 手指触摸的时候的状态
             *                     AbsListView.OnScrollListener.SCROLL_STATE_FLING 惯性
             */
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        //获取到最后一条显示的数据
                        int lastVisiblePosition = listView.getLastVisiblePosition();
                        System.out.println("lastVisiblePosition==========" + lastVisiblePosition);
                        if (lastVisiblePosition == list.size() - 1) {
                            initData();
                        }
                        break;
                }
            }

            //listview滚动的时候调用的方法
            //时时调用。当我们的手指触摸的屏幕的时候就调用
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
    }

    private void initData() {
        total = dao.getTotalNumber();//必要，查询最新总数，如果已经见底将赋值给mStartIndex
        new Thread() {
            @Override
            public void run() {
                //分批加载数据
                if (list == null) {
                    System.out.println("1==========" + 0 + "；Toast_mStartIndex: " + mStartIndex + "；total: " + total);
                    list = dao.findPar2(mStartIndex, maxCount);
                    // 如果查询数>total, 取total为下一个起点
                    if ((mStartIndex += maxCount) > total) {
                        mStartIndex = total;
                    }
                } else if (list.size() < total) {
                    System.out.println("2==========" + list.size() + "；Toast_mStartIndex: " + mStartIndex + "；total: " + total);
                    //把后面的数据。追加到blackNumberInfos集合里面。防止黑名单被覆盖
                    list.addAll(dao.findPar2(mStartIndex, maxCount));
                    if ((mStartIndex += maxCount) > total) {
                        mStartIndex = total;
                    }
                } else {
                    System.out.println("3==========" + list.size() + "；Toast_mStartIndex: " + mStartIndex + "；total: " + total);
                    //不加载
                    mStartIndex = total;//让数据回去最后一个开始点
                    //不能在子线程中弹Toast，弹要加下面两句
                    Looper.prepare();
                    Toast.makeText(CallSafe2Activity.this,"没有更多的数据了。", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                    return;
                }
                handler.sendEmptyMessage(0);
            }
        }.start();

    }

    public void addBlackCall(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("新增黑名单");
        builder.setIcon(R.drawable.ic_delete_btn_focused);
        View v = View.inflate(this, R.layout.dialog_add_black_call, null);
        builder.setView(v);
        final EditText addBlackCall = (EditText) v.findViewById(R.id.et_add_black_call);
        final CheckBox cbCall = (CheckBox) v.findViewById(R.id.cb_forbid_call);
        final CheckBox cbMsg = (CheckBox) v.findViewById(R.id.cb_forbid_msg);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String phone = addBlackCall.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(CallSafe2Activity.this, "请添加号码", Toast.LENGTH_SHORT).show();
                    return;
                }
                String mode;
                if (cbCall.isChecked() && cbMsg.isChecked()) {
                    mode = String.valueOf(3);
                } else if (cbCall.isChecked()) {
                    mode = String.valueOf(1);
                } else if (cbMsg.isChecked()) {
                    mode = String.valueOf(2);
                } else {
                    Toast.makeText(CallSafe2Activity.this, "请选择拦截方式", Toast.LENGTH_SHORT).show();
                    return;
                }
                boolean res = dao.save(phone, mode);
                if (res) {
                    Toast.makeText(CallSafe2Activity.this, "添加成功", Toast.LENGTH_SHORT).show();
                    initData();
                } else {
                    Toast.makeText(CallSafe2Activity.this, "失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder.show();
    }


}
